package com.sky.myTask;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理订单超时定时处理 每分钟执行一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOut(){
        log.info("定时处理超时订单");
        LocalDateTime orderOverTime = LocalDateTime.now().plusMinutes(-15);
        //查询超时订单
        List<Orders> orders = orderMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT,orderOverTime);

        orders.forEach(order -> {
            //修改超时订单为取消状态
            //设置订单id
            order.setId(order.getId());
            //设置取消原因
            order.setCancelReason("超时未知,自动取消");
            //设置订单状态
            order.setStatus(Orders.CANCELLED);
            //设置取消时间
            order.setCancelTime(LocalDateTime.now());

            orderMapper.update(order);
        });
    }

    /**
     * 派送中订单定时处理 每日凌晨1点执行一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processDelivery(){
        log.info("定时处理派送中订单");
        //查询前一天派送状态订单
        //查询前1天的订单时间小于当天凌晨1点订单时间的订单
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> orders = orderMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, localDateTime);

        //修订单状态为已送达
        orders.forEach(order -> {
            //修改派送状态订单为已完成状态
            //设置订单状态
            order.setStatus(Orders.COMPLETED);

            orderMapper.update(order);
        });
    }

}
